package xin.infinite.service;


import org.apache.dubbo.config.annotation.Service;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@Service
@org.springframework.stereotype.Service
public class MailServiceImpl implements MailService {

    @Resource
    private JavaMailSender mailSender;
    /**
     *
     * @param mailFrom     发件人邮箱
     * @param mailFromNick 发件人昵称
     * @param mailTo       收件人邮箱
     * @param cc           抄送人邮箱(可为空，方法内部处理)
     * @param subject      主题
     * @param content      内容
     * @return
     */
    public boolean sendSimpleMail(String mailFrom, String mailFromNick, String mailTo, String cc, String subject, String content) {
        try {
            String[] mailToStr=mailTo.split(",");
            for (String i : mailToStr) {
                MimeMessage mimeMessage = mailSender.createMimeMessage();
                MimeMessageHelper mimeMessageHelper=new MimeMessageHelper(mimeMessage);
                // 昵称
                mimeMessageHelper.setFrom(new InternetAddress(mailFromNick + " <" + mailFrom + ">"));
                mimeMessageHelper.setTo(i);
                if (!StringUtils.isEmpty(cc)) {
                    //抄送
                    mimeMessageHelper.setCc(cc);
                }
                mimeMessageHelper.setSubject(subject);
                mimeMessageHelper.setText(content);
                mailSender.send(mimeMessage);
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public boolean sendCodeEmail(String email, String code) {

        return sendSimpleMail("814050439@qq.com","工具人",email,null,"验证码",code);
    }
}
